﻿using System;
using System.Collections;
using System.Collections.Generic;
 using System.ComponentModel;
using System.Configuration.Install;
using System.Text.RegularExpressions;
using System.IO;
using System.Data;
using System.Data.SqlClient;
using System.Windows.Forms;
using System.Reflection;
using System.Security.Principal;
using Microsoft.SqlServer.Management.Smo;
using Microsoft.SqlServer.Management.Common;
namespace InstallSQLServerHealthCheckDatabase
{
    [RunInstaller(true)]
    public partial class SQLServerHealthCheckDBInstaller : System.Configuration.Install.Installer
    {
        public SQLServerHealthCheckDBInstaller()
        {
            InitializeComponent();
        }

        public override void Install(IDictionary stateSaver)
        {
            base.Install(stateSaver);

            RunDBSetup(Context.Parameters["dbname"].ToString());
        }

        public bool RunDBSetup(string databaseserver)
        {

            try
            {
                if (System.Security.Principal.WindowsIdentity.GetCurrent().IsAnonymous)
                {
                    MessageBox.Show(@"Please note you are using  ANONYMOUS LOGIN for installation.It seems there are issues with Kerberos tickets.Please fix that or add  NTAUTHORITY\ANONYMOUS LOGIN in SQL Server instance and give it a sysadmin rights.", "SQLServerHealthCheck", MessageBoxButtons.OK, MessageBoxIcon.Information);

                }
                else
                {
                    MessageBox.Show("The installation will proceed under the account   ' " + System.Security.Principal.WindowsIdentity.GetCurrent().Name.ToString() + " ' .Please make sure that the account has enough rights in SQL Server as well as in installation folder.", "SQLServerHealthCheck", MessageBoxButtons.OK, MessageBoxIcon.Information);
                }
                
                string FileName = Application.StartupPath + @"\SQLServerHealthCheck.Database.sql";


                ReplaceInFile(FileName, @":setvar DefaultDataPath """"", string.Empty);
                ReplaceInFile(FileName, @":setvar DefaultLogPath """"", string.Empty);
                databaseserver = databaseserver.Replace(@"\\", @"\");
                string CommandLineString = "-S" + databaseserver + " -vDefaultDataPath=" + @"""" + GetDataFilePath(databaseserver) + @""" -i""" + FileName + @"""";
                CommandLineString = CommandLineString.Replace(@"\\", @"\");

                System.Diagnostics.ProcessStartInfo myInfo = new System.Diagnostics.ProcessStartInfo("SQLCMD", CommandLineString);
                myInfo.UseShellExecute = false;
                myInfo.CreateNoWindow = true;
                myInfo.RedirectStandardOutput = true;

                System.Diagnostics.Process p = new System.Diagnostics.Process();
                p.StartInfo = myInfo;
                p.Start();
                //wait 5 seconds for this to finish
                System.Threading.Thread.Sleep(10000);


                //FileInfo fileInfo = new FileInfo(FileName);
                //string script = fileInfo.OpenText().ReadToEnd();
                //SqlConnection connection = new SqlConnection(System.Configuration.ConfigurationManager.AppSettings["ConnectionStringTemplate"].ToString());
                //Server server = new Server(new ServerConnection(connection));
                //server.ConnectionContext.ExecuteNonQuery(script);

            }

            catch (SqlException sqex)
            {
                MessageBox.Show(sqex.Message.ToString());
            }

            catch (Exception ex)
            {
                MessageBox.Show(ex.Message.ToString() );
            }
            return true;

        }


        private string GetDataFilePath(string databaseserver)
        {
            string strDataFilepath = "";
            try
            {
               
                SqlConnection conn = new SqlConnection(@"Server=" + databaseserver + ";Database=master;Integrated Security=True");
                conn.Open();
                SqlCommand ocmd = new SqlCommand("select SUBSTRING([filename],0, CHARINDEX([name],[filename],0)) as DataFilePath from sys.sysaltfiles where dbid=1 and fileid=1", conn);
                SqlDataReader rd = ocmd.ExecuteReader();

                if (rd.Read())
                {

                    strDataFilepath = rd["DataFilePath"].ToString();
                }

                rd.Close();
            
            }
            catch (SqlException sqex)
            {
                MessageBox.Show(sqex.Message.ToString());
            }

           
            return strDataFilepath;
          
        }

        private string GetLogFilePath(string databaseserver)
        {
            string strLogFilepath = "";
            try
            {
                SqlConnection conn = new SqlConnection(@"Server=" + databaseserver + ";Database=master;IntegratedSecurity=true");
                conn.Open();
                SqlCommand ocmd = new SqlCommand("select SUBSTRING([filename],0, CHARINDEX([name],[filename],0))  as LogFilePath from sys.sysaltfiles where dbid=1 and fileid=2", conn);
                SqlDataReader rd = ocmd.ExecuteReader();

                if (rd.Read())
                {

                    strLogFilepath = rd["LogFilePath"].ToString();
                }

                rd.Close();
            }
            catch (SqlException sqex)
            {
                MessageBox.Show(sqex.Message.ToString());
            }


            return strLogFilepath;

        }


        public void ReplaceInFile(string filePath, string searchText, string replaceText)
        {
            StreamReader reader = new StreamReader(filePath);
            string content = reader.ReadToEnd();
            reader.Close();

            content = Regex.Replace(content, searchText, replaceText);

            StreamWriter writer = new StreamWriter(filePath);
            writer.Write(content);
            writer.Close();
        }

    }
}
